package com.finddeer.bookkeeping.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.finddeer.bookkeeping.Bill;
import com.finddeer.bookkeeping.BillLab;
import com.finddeer.bookkeeping.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;

/**
 * author    : leaves
 * gitee     : https://gitee.com/LEAVES2018
 * time      : 2018/12/24 12:12 AM
 * function  : 账单详情页Fragment。显示及修改金额、详细信息、标签、消费时间、地点等数据。
 */
public class BillFragment extends Fragment {

    private static final String ARG_BILL_ID = "bill_id";
    private static final String DIALOG_DATE = "DialogDate";
    private static final String DIALOG_TIME = "DialogTime";

    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_TIME = 1;

    private Bill mBill;

    private EditText mAmountEditText;
    private EditText mTitleEditText;
    private Button mDateButton;
    private Button mTimeButton;
    private EditText mLocaleEditText;

    private Button mDietTagButton;
    private Button mTrafficTagButton;
    private Button mFunTagButton;
    private Button mStudyTagButton;
    private Button mShopTagButton;
    private Button mCureTagButton;
    private Button mInvestTagButton;
    private Button mLoveTagButton;


    public static BillFragment newInstance(UUID billId) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_BILL_ID, billId);

        BillFragment fragment = new BillFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        UUID billId = (UUID) getArguments().getSerializable(ARG_BILL_ID);
        mBill = BillLab.get(getActivity()).getBill(billId);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bill, container, false);

        mTitleEditText = view.findViewById(R.id.bill_title);
        mTitleEditText.setText(mBill.getTitle());
        mTitleEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mBill.setTitle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        String[] data = {"餐饮", "交通", "娱乐", "学习", "购物", "医疗", "投资", "情意"};

        mDietTagButton = view.findViewById(R.id.diet_tag_button);
        mDietTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mDietTagButton.getText()+" ");
                mBill.setTag(mDietTagButton.getText().toString());
            }
        });

        mTrafficTagButton = view.findViewById(R.id.traffic_tag_button);
        mTrafficTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mTrafficTagButton.getText()+" ");
                mBill.setTag(mTrafficTagButton.getText().toString());
            }
        });

        mFunTagButton = view.findViewById(R.id.fun_tag_button);
        mFunTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mFunTagButton.getText()+" ");
                mBill.setTag(mFunTagButton.getText().toString());
            }
        });

        mStudyTagButton = view.findViewById(R.id.study_tag_button);
        mStudyTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mStudyTagButton.getText()+" ");
                mBill.setTag(mStudyTagButton.getText().toString());
            }
        });

        mShopTagButton = view.findViewById(R.id.shop_tag_button);
        mShopTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mShopTagButton.getText()+" ");
                mBill.setTag(mShopTagButton.getText().toString());
            }
        });

        mCureTagButton = view.findViewById(R.id.cure_tag_button);
        mCureTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mCureTagButton.getText()+" ");
                mBill.setTag(mCureTagButton.getText().toString());
            }
        });

        mInvestTagButton = view.findViewById(R.id.invest_tag_button);
        mInvestTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mInvestTagButton.getText()+" ");
                mBill.setTag(mInvestTagButton.getText().toString());
            }
        });

        mLoveTagButton = view.findViewById(R.id.love_tag_button);
        mLoveTagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mTitleEditText.getSelectionStart();
                Editable editable = mTitleEditText.getText();
                editable.insert(index, "#"+mLoveTagButton.getText()+" ");
                mBill.setTag(mLoveTagButton.getText().toString());
            }
        });

        //  TODO 为什么清空时会闪退？
        mAmountEditText = view.findViewById(R.id.bill_amount);
        if (mBill.getAmount() != (double)0) {
            mAmountEditText.setText(mBill.getAmount() + "");
        }
        mAmountEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mDateButton = view.findViewById(R.id.bill_date);
        updateDate();
        mDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getFragmentManager();
                DatePickerFragment dialog = DatePickerFragment.newInstance(mBill.getDate());
                dialog.setTargetFragment(BillFragment.this, REQUEST_DATE);
                dialog.show(fm, DIALOG_DATE);
            }
        });

        mTimeButton = view.findViewById(R.id.bill_time);
        updateTime();
        mTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getFragmentManager();
                TimePickerFragment dialog = TimePickerFragment.newInstance(mBill.getDate());
                dialog.setTargetFragment(BillFragment.this, REQUEST_TIME);
                dialog.show(fm, DIALOG_TIME);
            }
        });

        mLocaleEditText = view.findViewById(R.id.bill_locale);
        mLocaleEditText.setText(mBill.getLocale());
        mLocaleEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mBill.setLocale(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_bill, menu);
    }

    //  TODO 直接按返回按钮时（Android系统底部三个导航按钮中的返回键），仍然会将空的Bill加入。如何解决？
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete:
                BillLab.get(getActivity()).deleteBill(mBill);
                getActivity().finish();
                return true;
            case R.id.check:
                String amount = mAmountEditText.getText().toString();
                if (!amount.isEmpty()) {
                    mBill.setAmount(Double.parseDouble(amount));
                }
                getActivity().finish();
                return true;
            default:
                if (mAmountEditText.getText().toString().isEmpty()) {
                    BillLab.get(getActivity()).deleteBill(mBill);
                }   //  当数额为空的时候，当前账单无效，删去（即：点击"+"后没有填写数额便返回算作无效）
                getActivity().finish();
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        BillLab.get(getActivity()).updateBill(mBill); //  更新mBill数据
    }

    //  该方法未被调用
    //  已解决：误将requestCode写成resultCode！！！自动补全太快，没有注意……
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_DATE:
                Date date = (Date) data
                        .getSerializableExtra(DatePickerFragment.EXTRA_DATE);
                mBill.setDate(date);
                updateDate();   //  updateDate()方法没有调用
                break;
            case REQUEST_TIME:
                Date date1 = (Date) data
                        .getSerializableExtra(TimePickerFragment.EXTRA_TIME);
                Calendar dateCalendar = Calendar.getInstance();
                dateCalendar.setTime(mBill.getDate());
                int year = dateCalendar.get(Calendar.YEAR);
                int month = dateCalendar.get(Calendar.MONTH);
                int day = dateCalendar.get(Calendar.DAY_OF_MONTH);
                Calendar timeCalendar = Calendar.getInstance();
                timeCalendar.setTime(date1);
                int hour = timeCalendar.get(Calendar.HOUR_OF_DAY);
                int minute = timeCalendar.get(Calendar.MINUTE);
                Date finalDate = new GregorianCalendar(year, month, day, hour, minute).getTime();
                mBill.setDate(finalDate);
                updateTime();
            default:
                break;
        }

    }

    private void updateDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        mDateButton.setText(simpleDateFormat.format(mBill.getDate()));
    }   //  将日期设置按钮上的信息设置为账单日期

    private void updateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("kk时mm分");
        mTimeButton.setText(simpleDateFormat.format(mBill.getDate()));
    }
}
